#!/usr/bin/env bash
###################
export DISPLAY=127.0.0.1:0
export PULSE_SERVER=tcp:127.0.0.1:4713
###############
TMOE_LINUX_DIR='/usr/local/etc/tmoe-linux'
TMOE_GIT_DIR="${TMOE_LINUX_DIR}/git"
TMOE_TOOL_DIR="${TMOE_GIT_DIR}/tools"
XSESSION_FILE='/etc/X11/xinit/Xsession'
TMOE_LOCALE_FILE="${TMOE_LINUX_DIR}/locale.txt"
RED=$(printf '\033[31m')
PURPLE=$(printf '\033[0;35m')
GREEN=$(printf '\033[32m')
YELLOW=$(printf '\033[33m')
BLUE=$(printf '\033[34m')
BOLD=$(printf '\033[1m')
RESET=$(printf '\033[m')
printf "${GREEN}%s ${YELLOW}%s${RESET} %s\n" "Starting" "x11" "..."
printf "%s\n" "The pulseaudio server is ${BLUE}${PULSE_SERVER}${RESET}"
printf "%s\n" "The display is ${BLUE}${DISPLAY}${RESET}"
stopvnc -non-stop-dbus 2>/dev/null
###############
check_tmoe_locale() {
	if [ -e "${TMOE_LOCALE_FILE}" ]; then
		TMOE_LANG=$(head -n 1 ${TMOE_LOCALE_FILE})
	else
		TMOE_LANG="zh_CN.UTF-8"
	fi
	export LANG="${TMOE_LANG}"
}
###########
notes_of_xserver() {
	case ${TMOE_LANG} in
	zh_*UTF-8)
		printf '%s\n' "正在为您启动${YELLOW}x11${RESET}..."
		printf "%s\n" "当前显示器为 ${BLUE}${DISPLAY}${RESET}"
		;;
		#*)
		#	printf '%s\n' 'Starting x11...'
		#	;;
	esac
	#printf '%s\033[32m%s\033[m%s\n' "您可以输" "stopvnc" "停止"
	#printf '%s \033[32m%s\033[m %s\n' "You can type" "stopvnc" "to stop it."
}
####################
start_windows_xserver() {
	VCXSRV_DISPLAY_PORT=37985
	. ${TMOE_LINUX_DIR}/wsl_pulse_audio
	cd "/mnt/c/Users/Public/Downloads/VcXsrv/"
	#/mnt/c/WINDOWS/system32/cmd.exe /c "start .\config.xlaunch"
	/mnt/c/WINDOWS/system32/taskkill.exe /f /im vcxsrv.exe 2>/dev/null
	/mnt/c/WINDOWS/system32/cmd.exe /c "start .\vcxsrv.exe :${VCXSRV_DISPLAY_PORT} -multiwindow -clipboard -wgl -ac"
	printf "%s\n" "若无法自动打开X服务，则请手动在资源管理器中打开C:\Users\Public\Downloads\VcXsrv\vcxsrv.exe"
	#if grep -q '172..*1' "/etc/resolv.conf"; then
	if [ "$(uname -r | cut -d '-' -f 2)" = "microsoft" ]; then
		printf "%s\n" "检测到您当前使用的可能是WSL2，如需手动启动，请在xlaunch.exe中勾选Disable access control"
		#WSL2IP=$(sed -n p /etc/resolv.conf | grep nameserver | awk '{print $2}' | head -n 1)
		WSL2IP=$(ip route list table 0 | head -n 1 | awk -F 'default via ' '{print $2}' | awk '{print $1}')
		export DISPLAY=${WSL2IP}:${VCXSRV_DISPLAY_PORT}
		printf "%s\n" "已将您的显示和音频服务ip修改为${WSL2IP}"
	else
		export DISPLAY="$(printf '%s\n' "${DISPLAY}" | cut -d ':' -f 1):${VCXSRV_DISPLAY_PORT}"
	fi
	sleep 2
}
###############
check_wsl() {
	if [ "$(uname -r | cut -d '-' -f 3)" = "Microsoft" ] || [ "$(uname -r | cut -d '-' -f 2)" = "microsoft" ]; then
		export TMOE_CHROOT='true'
		start_windows_xserver
	fi
}
###############
source_tmoe_dbus_daemon() {
	. ${TMOE_TOOL_DIR}/gui/launch_dbus_daemon
}
############
check_tmoe_locale
notes_of_xserver
check_wsl
source_tmoe_dbus_daemon
###########
. ${XSESSION_FILE} &
